package com.k.camera2

import android.Manifest
import android.content.pm.PackageManager
import android.hardware.Camera
import android.media.MediaRecorder
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.TextureView
import android.view.View
import android.view.View.OnClickListener
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File
import java.io.IOException

class MainActivity : AppCompatActivity(), OnClickListener {
    val TAG = "MainActivity"
    lateinit var textureView1: TextureView
    lateinit var textureView2: TextureView

    lateinit var imageView1: ImageView
    lateinit var imageView2: ImageView

    lateinit var ivCamera1: ImageView
    lateinit var ivCamera2: ImageView

    lateinit var ivVideo1: ImageView
    lateinit var ivVideo2: ImageView

    var previewCamera1 = PreviewCamera()
    var previewCamera2 = PreviewCamera()

    lateinit var allData1: ByteArray
    lateinit var allCamera1: Camera

    lateinit var allData2: ByteArray
    lateinit var allCamera2: Camera

    private val CAMERA_PERMISSION_CODE = 101
    private val WRITE_EXTERNAL_STORAGE = 102

    var isRecord1 = false
    var isRecord2 = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initView()
        requestCameraPermission()
    }

    private fun initView() {
        textureView1 = findViewById(R.id.tv1)
        textureView2 = findViewById(R.id.tv2)
        imageView1 = findViewById(R.id.iv1)
        imageView2 = findViewById(R.id.iv2)

        ivCamera1 = findViewById(R.id.iv_camera1)
        ivCamera2 = findViewById(R.id.iv_camera2)
        ivVideo1 = findViewById(R.id.iv_video1)
        ivVideo2 = findViewById(R.id.iv_video2)

        ivCamera1.setOnClickListener(this)
        ivCamera2.setOnClickListener(this)
        ivVideo1.setOnClickListener(this)
        ivVideo2.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_camera1 -> {
                showBitmapOne()
            }

            R.id.iv_camera2 -> {
                showBitmapTwo()
            }

            R.id.iv_video1 -> {
                saveVideoOne()
            }

            R.id.iv_video2 -> {
                saveVideoTwo()
            }
        }
    }

    /**
     * 录像
     */
    private fun saveVideoOne() {
        GlobalScope.launch(Dispatchers.IO) {
            if (isRecord1) {
                ivVideo1.setImageResource(R.mipmap.img_video_disable)
                isRecord1 = false
                stop1(allCamera1)
            } else {
                ivVideo1.setImageResource(R.mipmap.img_video_enabled)
                isRecord1 = true
                val path = PreviewCameraUtils.getSDCardPath() + "/HJ"
                val fileName = "Y_${System.currentTimeMillis()}"
                record1(allCamera1, 0, path, fileName)
            }
        }
    }

    /**
     * 录像
     */
    private fun saveVideoTwo() {
        GlobalScope.launch(Dispatchers.IO) {
            if (isRecord2) {
                ivVideo2.setImageResource(R.mipmap.img_video_disable)
                isRecord2 = false
                stop2(allCamera2)
            } else {
                ivVideo2.setImageResource(R.mipmap.img_video_enabled)
                isRecord2 = true
                val path = PreviewCameraUtils.getSDCardPath() + "/HJ"
                val fileName = "S_${System.currentTimeMillis()}"
                record2(allCamera2, 0, path, fileName)
            }
        }
    }

    private fun showBitmapOne() {
        val bitmap = PreviewCameraUtils.cameraDataToBitmap(allData1, allCamera1)
        val finalBitmap = PreviewCameraUtils.bitmapXform(bitmap, 180, false, false)
        imageView1.setImageBitmap(finalBitmap)
    }

    private fun showBitmapTwo() {
        val bitmap = PreviewCameraUtils.cameraDataToBitmap(allData2, allCamera2)
        val finalBitmap = PreviewCameraUtils.bitmapXform(bitmap, 180, false, false)
        imageView2.setImageBitmap(finalBitmap)
    }


    private fun requestCameraPermission() {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.CAMERA),
                CAMERA_PERMISSION_CODE
            )
        } else {
            requestStoragePermission()
        }
    }

    private fun requestStoragePermission() {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                CAMERA_PERMISSION_CODE
            )
        } else {
            openCamerasOne()
            openCamerasTwo()
        }
    }

    private fun requestRecordAudioPermission() {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.RECORD_AUDIO
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                CAMERA_PERMISSION_CODE
            )
        } else {
            openCamerasOne()
            openCamerasTwo()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == CAMERA_PERMISSION_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Camera permission granted", Toast.LENGTH_SHORT).show()
                requestStoragePermission()
            } else {
                Toast.makeText(this, "Camera permission denied", Toast.LENGTH_SHORT).show()
            }
        }

        if (requestCode == WRITE_EXTERNAL_STORAGE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "STORAGE permission granted", Toast.LENGTH_SHORT).show()
                openCamerasOne()
                openCamerasTwo()
            } else {
                Toast.makeText(this, "STORAGE permission denied", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun openCamerasOne() {
        previewCamera1.setMirror(false) //   镜像
        previewCamera1.setRotate(180) // 旋转角度
//        previewCamera1.setZoom(50) // 焦距
        previewCamera1.startCamera(textureView1, 0, 640, 480, object : PreviewCamera.ICallback {
            override fun onSucc(camera: Camera) {
            }

            override fun onData(data: ByteArray, camera: Camera) {
                allData1 = data
                allCamera1 = camera
            }

            override fun onError(e: Exception) {
            }

        })
    }

    private fun openCamerasTwo() {
        previewCamera2.setMirror(true) //   镜像
        previewCamera2.setRotate(180) // 旋转角度
//        previewCamera1.setZoom(50) // 焦距
        previewCamera2.startCamera(textureView2, 1, 640, 480, object : PreviewCamera.ICallback {
            override fun onSucc(camera: Camera) {
            }

            override fun onData(data: ByteArray, camera: Camera) {
                allData2 = data
                allCamera2 = camera
            }

            override fun onError(e: Exception) {
            }

        })
    }

    override fun onStop() {
        super.onStop()

        previewCamera1.stopCamera()
        previewCamera2.stopCamera()
    }


    /**
     * 录制视频
     */

    lateinit var mediaRecorder1: MediaRecorder // 创建 MediaRecorder 实例
    lateinit var mediaRecorder2: MediaRecorder // 创建 MediaRecorder 实例

    /**
     * 录制视频
     */
    fun record1(camera: Camera, current_camera: Int, filePath: String, fileName: String) {
        Log.d(TAG, "record: 开始录制") // 输出日志，表示开始录制
        mediaRecorder1 = MediaRecorder() // 创建 MediaRecorder 实例
        camera.unlock() // 解锁相机

        mediaRecorder1.setCamera(camera) // 设置要使用的相机

        // 设置视频源
        mediaRecorder1.setVideoSource(MediaRecorder.VideoSource.DEFAULT)

        // 设置输出格式为 MPEG-4
        mediaRecorder1.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)

        // 设置视频编码格式为 H.264
        mediaRecorder1.setVideoEncoder(MediaRecorder.VideoEncoder.H264)

        // 设置视频大小为 1920x1080
        mediaRecorder1.setVideoSize(1920, 1080)

        // 设置视频编码比特率为 5Mbps
        mediaRecorder1.setVideoEncodingBitRate(5 * 1024 * 1024)

        // 设置视频帧率为 fps
        mediaRecorder1.setVideoFrameRate(30)

        // 根据当前相机设置视频文件的翻转角度
        if (current_camera == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            mediaRecorder1.setOrientationHint(180)
        } else if (current_camera == Camera.CameraInfo.CAMERA_FACING_BACK) {
            mediaRecorder1.setOrientationHint(180)
        }

        val file = File(filePath)
        if (!file.exists()) {
            file.mkdirs()
        }

        // 输出日志，显示录制视频的文件路径
        Log.e(TAG, "文件路径：${filePath}${File.separator}${fileName}.mp4")

        // 设置输出文件的路径
        mediaRecorder1.setOutputFile("${file.path}${File.separator}${fileName}.mp4")

        // 准备录制并开始录制视频
        try {
            mediaRecorder1.prepare()
            mediaRecorder1.start()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }


    /**
     * 录制视频
     */
    fun record2(camera: Camera, current_camera: Int, filePath: String, fileName: String) {
        Log.d(TAG, "record: 开始录制") // 输出日志，表示开始录制
        mediaRecorder2 = MediaRecorder() // 创建 MediaRecorder 实例
        camera.unlock() // 解锁相机

        mediaRecorder2.setCamera(camera) // 设置要使用的相机

        // 设置视频源
        mediaRecorder2.setVideoSource(MediaRecorder.VideoSource.DEFAULT)

        // 设置输出格式为 MPEG-4
        mediaRecorder2.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)

        // 设置视频编码格式为 H.264
        mediaRecorder2.setVideoEncoder(MediaRecorder.VideoEncoder.H264)

        // 设置视频大小为 1920x1080
        mediaRecorder2.setVideoSize(1920, 1080)

        // 设置视频编码比特率为 5Mbps
        mediaRecorder2.setVideoEncodingBitRate(5 * 1024 * 1024)

        // 设置视频帧率为 fps
        mediaRecorder2.setVideoFrameRate(30)

        // 根据当前相机设置视频文件的翻转角度
        if (current_camera == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            mediaRecorder2.setOrientationHint(180)
        } else if (current_camera == Camera.CameraInfo.CAMERA_FACING_BACK) {
            mediaRecorder2.setOrientationHint(180)
        }

        val file = File(filePath)
        if (!file.exists()) {
            file.mkdirs()
        }

        // 输出日志，显示录制视频的文件路径
        Log.e(TAG, "文件路径：${filePath}${File.separator}${fileName}.mp4")

        // 设置输出文件的路径
        mediaRecorder2.setOutputFile("${file.path}${File.separator}${fileName}.mp4")

        // 准备录制并开始录制视频
        try {
            mediaRecorder2.prepare()
            mediaRecorder2.start()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }


    /**
     * 停止录制
     */
    fun stop1(camera: Camera) {
        camera.lock() // 锁定相机
        mediaRecorder1.stop() // 停止录制
        mediaRecorder1.release() // 释放资源
//        openCamera(Camera.CameraInfo.CAMERA_FACING_BACK, surface) // 启动后置摄像头预览，可以根据之前使用的相机来判断
        Log.d(TAG, "stop1: 录制完成") // 输出日志，表示录制完成
    }

    /**
     * 停止录制
     */
    fun stop2(camera: Camera) {
        camera.lock() // 锁定相机
        mediaRecorder2.stop() // 停止录制
        mediaRecorder2.release() // 释放资源
//        openCamera(Camera.CameraInfo.CAMERA_FACING_BACK, surface) // 启动后置摄像头预览，可以根据之前使用的相机来判断
        Log.d(TAG, "stop2: 录制完成") // 输出日志，表示录制完成
    }
}
